from base.views import TemplateView, ActionView

from flask import Blueprint, redirect, url_for, request
from flask_login import login_required, logout_user, login_user

from models import User
from utils import get_param
from flask import jsonify

auth = Blueprint('auth', __name__)


class LoginView(TemplateView):
    template_name = 'auth/login.html'

    def post(self):
        if request.is_xhr:
            data = {}
            username = get_param('username', 'string', required=True,
                max_length=64, min_length=1)
            password = get_param('password', 'string', required=True,
                max_length=64, min_length=1)
            user = User.query.filter_by(username=username, password=password).first()
            if user:
                login_user(user, remember=True)
                return jsonify({
                    'ret': 20000,
                    'redirect': get_param('next', 'string', required=False, default=url_for('front.index'))
                })
            else:
                return jsonify({
                    'ret': 30000,
                    'msg': '登陆失败'
                })
        return self.get()


class LogoutView(ActionView):
    decorators = [login_required, ]

    def get(self, *args, **kwargs):
        logout_user()
        return redirect(get_param('next', 'string', default='/'))


def register():
    auth.add_url_rule('/login', view_func=LoginView.as_view('login'))
    auth.add_url_rule('/logout', view_func=LogoutView.as_view('logout'))